package md.frolov.bible.indexes;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List;

import md.frolov.bible.Activator;
import md.frolov.bible.Constants;

public abstract class IX {
	protected File file;
	protected long lastModified;
	protected List<String> keys = new ArrayList<String>(1200);
	protected List<Long> offsets = new ArrayList<Long>(1200);
		
	public IX(File file){
		this(file, file.lastModified());
	}
	
	public IX(File file, long lastModified){
		this.lastModified=lastModified;
		this.file = file;
	}
	
	public void addOffset(String key, long offset){
		keys.add(key);
		offsets.add(offset);
	}
	
	public File getFile(){
		return file;
	}
	
	public abstract long getOffset(String key);
	
	public void save(File path) throws IOException{
		File f = new File(path.getAbsolutePath()+generateFileName());
		
		if(f.exists()){
			//nothing to save
			return;
		}
		
		if(!f.createNewFile()){
			System.out.println("won't write index");
			return;
		}
		
		BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(f),Constants.ENCODING));
		try{
			bw.write(file.getAbsolutePath().substring(Activator.getInstance().getWorkspace().toFile().getAbsolutePath().length()));
			bw.newLine();
			bw.write(String.valueOf(lastModified));
			bw.newLine();
			bw.write(getType());
			bw.newLine();
			
			for(int i=0;i<keys.size();i++){
				bw.write(keys.get(i));
				bw.newLine();
				bw.write(String.valueOf(offsets.get(i)));
				bw.newLine();
			}
			
		}  catch (Exception e){
			System.out.println("something went wrong");
			bw.flush();
		} finally {
			bw.close();
		}
	}
	
	public String generateFileName(){
		return File.separatorChar+file.getName()+"."+lastModified+".ix";
	}
	
	public long lastModified(){
		return lastModified;
	}
	
	public abstract String getType();
}
